package com.cskaoyan.market.service.impl;

import com.cskaoyan.market.db.domain.MarketRegion;
import com.cskaoyan.market.db.domain.MarketRegionExample;
import com.cskaoyan.market.db.mapper.MarketRegionMapper;
import com.cskaoyan.market.service.AdminRegiomService;
import com.cskaoyan.market.util.MybatisUtils;
import com.cskaoyan.market.vo.RegionListVo;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author:yanzijun
 * @time:2024/06/20/21:22
 */
public class AdminRegionServiceImpl implements AdminRegiomService {

    @Override
    public List<RegionListVo> list() {
        SqlSession session = MybatisUtils.getSession();
        MarketRegionMapper mapper = session.getMapper(MarketRegionMapper.class);
        List<MarketRegion> marketRegions = mapper.selectByExample(new MarketRegionExample());
        session.close();
        HashMap<Integer, List<MarketRegion>> stringListHashMap = gropByPid(marketRegions);
        ArrayList<RegionListVo> vos = new ArrayList<>();
        //得到省份的list
        List<MarketRegion> l1Region = stringListHashMap.get(0);
        for (MarketRegion province : l1Region) {
            //得到市级的list
            List<RegionListVo> l2Region = new ArrayList<>();
            RegionListVo provinceVo = new RegionListVo(province.getId(), province.getName(), province.getType(), province.getCode(), l2Region);
            for (MarketRegion city : stringListHashMap.get(province.getId())) {
                List<RegionListVo> l3Region = new ArrayList<>();
                RegionListVo cityVo = new RegionListVo(city.getId(), city.getName(), city.getType(), city.getCode(), l3Region);
                for (MarketRegion area : stringListHashMap.get(city.getId())) {

                    RegionListVo areaVo = new RegionListVo(area.getId(), area.getName(), area.getType(), area.getCode(), null);

                    l3Region.add(areaVo);
                }


                l2Region.add(cityVo);

            }


            vos.add(provinceVo);
        }
        return vos;
    }

    private HashMap<Integer, List<MarketRegion>> gropByPid(List<MarketRegion> marketRegions) {
        HashMap<Integer, List<MarketRegion>> integerListHashMap = new HashMap<>();
        for (MarketRegion marketRegion : marketRegions) {
            Integer pid = marketRegion.getPid();
            List<MarketRegion> list = integerListHashMap.get(pid);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(marketRegion);
            integerListHashMap.put(pid, list);
        }
        return integerListHashMap;
    }
}
